package com.atzxh.java;

public class Lock {

    static Object lockA = new Object();
    static Object lockB = new Object();

    public static void main(String[] args) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "尝试获取A");
                synchronized (lockA) {
                    System.out.println(Thread.currentThread().getName() +"获取到A");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "尝试获取B");
                    synchronized (lockB) {
                        System.out.println(Thread.currentThread().getName() +"获取到B");
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "尝试获取B");
                synchronized (lockB) {
                    System.out.println(Thread.currentThread().getName() +"获取到B");
                    System.out.println(Thread.currentThread().getName() + "尝试获取A");
                    synchronized (lockA) {
                        System.out.println(Thread.currentThread().getName() +"获取到A");
                    }
                }
            }
        }).start();
    }
}

